package com.jy.modules.cims.auxiliary.Controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jy.modules.cims.auxiliary.service.CreditSettleBillService;
import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.JResult;
import com.jy.modules.cims.common.controller.ExportController.ExportUtil;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.common.sysUtils.ExceptionUtils;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.sysAssist.ExportAndImport;
import com.jy.modules.cims.data.common.dto.TCMmTaskLogDTO;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.CreditPackageDto;
import com.jy.modules.cims.data.dto.CreditSettleBillDto;
import com.jy.modules.cims.settle.service.SettleService;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;
import com.jy.platform.restservice.web.base.BaseController;
/**
 * 债权转让结算台账
 * ClassName: CreditSettleBillController 
 * @Description: TODO
 * @author zhoupeng
 * @date 2015-12-15
 */
@Controller
@Scope("prototype")
@RequestMapping("/creditsettlebill")
public class CreditSettleBillController extends BaseController {
	
	@Autowired
	@Qualifier("com.jy.modules.cims.auxiliary.service.CreditSettleBillService")
	public CreditSettleBillService creditSettleBillService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.settle.service.SettleService")
	public SettleService settleService;
	
	@RequestMapping(value = "/prepareExecute/{operate}")
    public ModelAndView execute(@PathVariable("operate") String operate) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        if("toQuery".equals(operate)){//跳转至 查询页面
            model.setViewName("cims/auxiliaryFunction/queryCreditSettleBill");
            return model;
        }
        return model;
	}
	
	@RequestMapping(value = "/queryCreditSettleBillList")
	@ResponseBody
	public DataMsg queryCreditSettleBillList(HttpServletRequest request,HttpServletResponse response,CreditSettleBillDto dto, @ModelAttribute DataMsg dataMsg)throws Exception{
		response.reset();
		try {
		Map<String, Object> searchParams = new HashMap<String, Object>();
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		if(SimpleStringUtils.hasText(dto.getCooperorgCode())){//如果有合作机构，合约，时间才进行查询
			searchParams.put("dto", dto);
			
			List<CreditSettleBillDto> list = creditSettleBillService.searchCreditSettleBillDtoByPaging(params.getSearchParams());
		    dataMsg.setData(list);
		}else{
			dataMsg.setData(null);
		}
		
        dataMsg.setTotalRows(pageInfo.getTotalCount());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dataMsg;
	}
	/**
	 * 
	 * @Description  计算总是请求
	 * @author zhoupeng
	 * @date 2015-12-17
	 */
	@RequestMapping(value = "/getCreditSettleBillSum")
	@ResponseBody
	public DataMsg getCreditSettleBillSum(HttpServletRequest request,CreditSettleBillDto dto, @ModelAttribute DataMsg dataMsg)throws Exception{
		try {
		Map<String, Object> searchParams = new HashMap<String, Object>();
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		if(SimpleStringUtils.hasText(dto.getCooperorgCode())){//如果有合作机构，合约，时间才进行查询
			searchParams.put("dto", dto);
			//List<CreditSettleBillDto> listSum=null;
			List<CreditSettleBillDto> listSum = creditSettleBillService.getCreditSettleBillSum(params.getSearchParams());
			if(CollectionsUtils.isNotEmpty(listSum)){
			    dataMsg.setData(listSum);
			}else{
				dataMsg.setData(listSum);
			}
		}else{
			dataMsg.setData(null);
		}
        dataMsg.setTotalRows(pageInfo.getTotalCount());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dataMsg;
	}
	/**
	 * 
	 * @Description 导出--月还结算
	 * exportCreditSettleBillList  
	 * @author zhoupeng
	 * @date 2015-12-17
	 */
	@RequestMapping(value = "/exportCreditSettleBillList")
    public ModelAndView exportCreditSettleBillList(HttpServletRequest request, CreditSettleBillDto dto, HttpServletResponse response,@ModelAttribute DataMsg dataMsg){
    	try {
		        Map<String, Object> searchParams = new HashMap<String, Object>();
		        QueryReqBean params = new QueryReqBean();
		        params.setSearchParams(searchParams);
		    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
				params.setPageParameter(pageInfo);
				List<CreditSettleBillDto> list =new ArrayList<CreditSettleBillDto>();
				if(SimpleStringUtils.hasText(dto.getCooperorgCode())){//如果有合作机构，合约，时间才进行查询
					searchParams.put("dto", dto);
				
					list = creditSettleBillService.exportCreditSettleBillDtoList(params.getSearchParams());
				    dataMsg.setData(list);
				}
		    	ExportAndImport<CreditSettleBillDto> eai = new ExportAndImport<CreditSettleBillDto>();
		        String fileName = "月还结算"+DateTimeUtils.getDateTime("yyyyMMddHHmmss");
		        String creditSettleBillCode = CimsConstant.CREDIT_SETTLEBILL_CODE;
		        String creditSettleBillName = CimsConstant.CREDIT_SETTLEBILL_NAME;
		        HSSFWorkbook workbook = eai.exportExcelSubsidiary(fileName, creditSettleBillCode, creditSettleBillName, list);
		        ExportUtil.write(workbook, fileName, response);
		    	return null;
	    	} catch (Exception e) {
	    		e.printStackTrace();
	            logger.error("异常:", e);
	            ModelAndView m = new ModelAndView();
	            m.setViewName("ccims/auxiliaryFunction/queryCreditSettleBill");
	            m.addObject("error", "导出报表异常！");
	            return m;
			}
    }
	
	/**
	 * 
	 * @Description 月还结算发送
	 * settleBillConfirm  
	 * @author zhoupeng
	 * @date 2016-03-12
	 */
	@RequestMapping(value = "/settleBillConfirm")
	@ResponseBody
	public DataMsg settleBillConfirm(HttpServletRequest request,HttpServletResponse response, CreditDetailDto queryDto, @ModelAttribute DataMsg dataMsg)throws Exception{
		response.reset();
		try {
			queryDto.setCostState(CimsConstant.COST_STATUS_DJ);
			JResult result = settleService.confirmSettle(queryDto);
			if(result.isSuccess()==false){
				 dataMsg.setStatus("error");
		         dataMsg.setMsg(result.getErrMsg());
			}else{
				dataMsg.setStatus("ok");
	        	dataMsg.setMsg("月还结算申请已发送！");
			}
		} catch (Exception e) {
			String errorInfo = ExceptionUtils.getStackTraceAsString(e);
            logger.error("执行方法costCreditSettleList异常-月还结算功能失败~:", e);
            dataMsg.setStatus("error");
        	dataMsg.setMsg(errorInfo);
		}
		return dataMsg;
	}
	
	/**
	 * @Description 调用实时月还和二次购买任务处理
	 * @author zhoupeng
	 * @date 2016-05-12
	 */
	@RequestMapping(value = "/dealSettleAndSecondBuy")
	@ResponseBody
	public DataMsg dealSettleAndSecondBuy(HttpServletRequest request,HttpServletResponse response, TCMmTaskLogDTO dto, @ModelAttribute DataMsg dataMsg)throws Exception{
		response.reset();
		try {
			
			String settleDate = DateTimeUtils.formatDate(dto.getSettleDate()==null?new Date():dto.getSettleDate(), "yyyy-MM-dd");
			CreditPackageDto creditPackageDto = new CreditPackageDto();
			creditPackageDto.setSettleDate(settleDate);
			JResult errResult= settleService.batchSettleAndSecondBuy(creditPackageDto, true);
			if(errResult.isSuccess()){
				dataMsg.setStatus("ok");
	        	dataMsg.setMsg("成功！");
			}else{
				dataMsg.setStatus("error");
	        	dataMsg.setMsg(errResult.getErrMsg());
			}
		} catch (Exception e) {
			String errorInfo = ExceptionUtils.getStackTraceAsString(e);
			
            logger.error("实时生成还款计划和结算计划失败~:", e);
            dataMsg.setStatus("error");
        	dataMsg.setMsg("实时生成还款计划和结算计划失败！\n<br>"+errorInfo);
		}
		return dataMsg;
	}
}
